<?php
namespace app\weixin\traits;

use think\Config;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use \app\common\libs\WeixinHelper;
use \app\common\model\WXUser;
use \app\common\libs\Tuling;
use \app\back\model\Account;
use \app\common\model\TmpMobile;
use \app\common\model\SmsMobile;
use \app\common\libs\WeixinTpl;
use \app\common\libs\Sms;

trait Weixin
{

	/*
	 * 添加微信关注记录
	 */
	function addSubscribe($wx_data) {
		$userdata = WeixinHelper::getWXUserInfo(\token(), $wx_data['FromUserName']);

		$weixin_user_model = new WXUser();
		$weixin_user_model->subscribe($userdata, $wx_data['ToUserName']);
	}
	/*
	 * 微信配置验证
	 */
	public function wxVerification(){
		//0)接收微信get方式传递过来的
		$signature = input('get.signature'); //微信加密签名
		$timestamp = input('get.timestamp'); //时间戳
		$nonce = input('get.nonce'); //随机数
		$echostr = input('get.echostr'); //随机字符串
		//file_put_contents('upload/1.txt', $signature.'#'.$timestamp.'#'.$nonce."#".$echostr);
		// 1）将token、timestamp、nonce三个参数进行字典序排序
		$token = config('weixin.token'); //自己设置,要和微信公众号平台填写的一致
		$arr = array($token, $timestamp, $nonce);
		sort($arr, SORT_STRING);

		//2）将三个参数字符串拼接成一个字符串进行sha1加密
		$str = implode($arr);
		$str = sha1($str);

		//3）开发者获得加密后的字符串可与signature对比，相同原样返回echostr参数内容, 确定请求来源于微信
		if ($str == $signature) {
			ob_clean();//清空之前的输出
			echo $echostr;
			exit;
		} else {
			exit('token验证失败!');
		}
	}

	/*
	 * 图灵回复
	 */
	public function tulingReply($wx_data) {
		$tuling = new Tuling;
        $result = $tuling->reply($wx_data);

		try{
		        $datas = $tuling->toWXData($result, $wx_data['FromUserName']);
		} catch(\Exception $e) {
			trace(json_encode($result), 'weixin');
			trace($e->getMessage(), 'error');
			$datas = [];
		}
		
        foreach ($datas as $key => $value) {
			WeixinHelper::kfMessage($value, \token());
		}
	}

	/*
	 * 开通会员
	 */
	public function registerAccount($wx_data) {
		// 首先查看是否有微信关注记录
		if(!WXUser::where('username', $wx_data['FromUserName'])->count()) {
			$this->addSubscribe($wx_data);
		}

		// 查看该微信用户是否已注册会员
		$account_model = new Account();
		$wx_exists = $account_model->WXAcountExists($wx_data['FromUserName']);

		if($wx_exists) {
			$text = "您已开通会员，无需重复开通。";
			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
		}

		// 标记进入注册模式
		$tmp_mobile_model = new TmpMobile;
		$tmp_mobile_model->openWeixinReigster($wx_data['FromUserName']);

		// 开启会员注册模式
		$text = "进入会员开通模式，\n请输入您要绑定的手机号...";
		// 发送消息
		die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
	}

	/*
	 * 微信注册，手机步骤
	 */
	public function wxRegisterMobile($wx_data) {
		$tmp_mobile_model = new TmpMobile;
		
		if($tmp_mobile_model->isOpenWeixinRegister($wx_data['FromUserName'])) {
			$mobile = trim($wx_data['Content']);

			// 发送手机验证码
			$sms_model  = new Sms();
			$send_res = $sms_model->sendVCode($mobile);
			if($send_res['state'] === false) {
				// 发送失败提示信息
				die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $send_res['msg']));		
			}

			// 发送成功，绑定注册手机
			$tmp_mobile_model->tmpBindMobile($wx_data['FromUserName'], $mobile);

			if($mobile_exists = Account::existsByMobile($mobile)) {
				$text = "会员".substr_replace($mobile, '****', 3, 4).".已存在/::!";
				$text .= "\n输入验证码，将绑定当前微信";
				$text .= "\n更改会员号，请输入其他手机号码/::D";
			} else
				$text = "请输入手机尾号".substr($mobile, 7, 4)."收到的短信验证码";

			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
		} else {
			$text = "如需开通会员，请点击：\n会员功能\n开通会员";
			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));		
		}
	}

	/*
	 * 微信注册，验证码步骤
	 */
	public function wxRegisterVcode($wx_data) {
		// 没有开启注册模式，或者注册模式结束，将消息交给图灵
		$tmp_model = new TmpMobile;
		if(!$tmp_model->isOpenWeixinRegister($wx_data['FromUserName'])) 
			return true;

		$vcode_model = new SmsMobile();
		$mobile = $tmp_model->getBindMobile($wx_data['FromUserName']);

		if(!$mobile) {
			$text = "请输入手机号，重新获取验证码";
			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));			
		}

		$validate_res = $vcode_model->validateCode($mobile ,$wx_data['Content']);

		if(!$validate_res['state']) {
			$text = "请输入正确的验证码，或者输入手机号，重新获取验证码";
			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
		}

		// 注册用户
		$account_model = new Account;
		$res = $account_model->registerWXAccount($mobile, $wx_data['FromUserName']);

		if(!$res) {
			$text = '很遗憾，开通失败！再来一次吧/::<';
			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));			
		}

		// 作废短信验证
		$vcode_model->finishCode($mobile);
		$tmp_model->finishRegister($wx_data['FromUserName']);

		// 参加新用户注册活动
		$account_money_model = new \app\back\model\AccountMoney;
		$account_money_model->newCustomerWelfare($mobile, config('websys.newuser_money'), 'weixin');

		// 添加新用户通知队列
		$queue_model = new \app\back\model\WeixinQueue;
		$queue_model->WeixinTplQueue($mobile, $wx_data['ToUserName'], $wx_data['FromUserName']);

		if(config('websys.newuser_money') > 0 && newuser_ticket())
			$text = '会员开通成功，小咿赠送您'.config('websys.newuser_money').'元体验金，稍候会发到会员帐户';
		else
			$text = '恭喜您，会员开通成功';

		die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
	}

	/*
	 * 获取消费码
	 */
	function getPayCode($wx_data) {
		$user_mobile = Account::getMobileByOpenid($wx_data['FromUserName']);

		if(!$user_mobile) {
			$text = '您未开通会员，暂时不能获取消费码/::(';
			die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
		}

		// $生成消费码
		$sms = new Sms;
		$res = $sms->createPayCode($user_mobile);
		if($res['state']) {
			$text = "这个码【{$res['code']}】价值千金，别轻易告诉别人";
		} else {
			$text = '他娘的，服务器没按时吃药，一会再来吧/::’(';
		}

		die(WeixinTpl::text($wx_data['ToUserName'], $wx_data['FromUserName'], $text));
	}

	/*
	 * 微信公众号菜单点击事件
	 */
	function wxClickEvent($wx_data) {
		switch ($wx_data['EventKey']) {
			case 'order_customer_register':
				// 微信注册
				$this->registerAccount($wx_data);
				break;
			case 'order_pay_code':
				// 获取消费码
				$this->getPayCode($wx_data);
				break;
			case 'order_customer_info':
				// 获取用户信息
				if(Account::where('wx_openid', $wx_data['FromUserName'])->count() < 1) {
					$text='您还未开通本店会员，现在开通，我免费送您体验金/::>';
					$message = WeixinTpl::kefuTextTpl($wx_data['FromUserName'], $text);
					// 发送消息未注册通知
					WeixinHelper::kfMessage($message, \token());					

					// 发送开通会员教程
					$message = WeixinTpl::kefuNewsTpl($wx_data['FromUserName'], config('weixin.wx_helper')['help_account']);
					WeixinHelper::kfMessage($message, token());
				} else {
					$account_model = new \app\back\model\WeixinQueue;
					$account_model->createInfoTplForWx($wx_data['FromUserName']);					
				}

				break;

			default :
				$config_model = new \app\common\model\Config();
				$media_id = $config_model->getOneCofnigValue($wx_data['EventKey'], 'wx_menu_click');

				if(is_null($media_id)) {
					// 没有查询查询到，就把店铺介绍发过去
					$media_id = config('weixin.wx_helper')['help_introduce'];
				}

				$message = WeixinTpl::kefuNewsTpl($wx_data['FromUserName'], $media_id);
				WeixinHelper::kfMessage($message, token());
				break;
		}
	}
}
